git pull

# 检查是否传递了参数
if [ $# -eq 0 ]; then
    echo "请输入环境参数 test 或 pre 或 prod"
else
    # 检查第一个参数是否为 "prod"
    if [ "$1" == "prod" ]; then
        echo "当前环境是生产环境 (prod)。"

        echo "install dependency..."
        npm install --registry=https://registry.npmmirror.com

        timestamp=$(date +"%y%m%d%H%M%S")
        # 生成目录名
        dir_name=".nuxt-$timestamp"

        if [ ! -d 'cache' ]; then
        # 如果不存在，则创建目录
        mkdir "cache"
        fi

        # 直接构建到备份目录
        BUILD_DIR=cache/$dir_name npm run build:prod

        echo "生成备份 cache/$dir_name"

        # 创建软链接
        ln -sfn cache/$dir_name .nuxt

        pm2 kill

        pm2 start ecosystem.config.js --only "car-nuxt-prod"

    elif [ "$1" == "test" ]; then 
        echo "当前环境是测试环境 (test)。"

        echo "install dependency..."
        npm install --registry=https://registry.npmmirror.com

        BUILD_DIR=cache npm run build:test

        rm -rf .nuxt

        mv cache .nuxt

        pm2 kill

        pm2 start ecosystem.config.js --only "car-nuxt-test"

    elif [ "$1" == "pre" ]; then 
        echo "当前环境是预发环境 (pre)。"

        echo "install dependency..."
        npm install --registry=https://registry.npmmirror.com

        BUILD_DIR=cache npm run build:pre

        rm -rf .nuxt

        mv cache .nuxt

        pm2 kill

        pm2 start ecosystem.config.js --only "car-nuxt-pre"

    else 
        echo "环境参数错误，请输入环境参数 test 或 pre 或 prod"
    fi
fi